<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\model;
use think\Model;
use think\facade\Db;
class FeedbackFieldModel extends Model{
    const modelFieldPath = 'data/feedbackFieldTemp/'; //字段模板路径
    protected $name = 'feedback_field';
    protected $pk = 'field_id';
    /**
     * 检查字段是否存在
     * $table 不带表前缀
     */
    public function field_exists($table, $field) {        
        $fields = $this->get_fields($table);
        return array_key_exists($field, $fields);
    } 
    /**
     * 获取表字段
     * $table 不带表前缀
     */
    public function get_fields($table) {
        $fields = array();
        $table = config('database.connections.mysql.prefix') . $table;
        $data = Db::query("SHOW COLUMNS FROM $table");
        foreach ($data as $v) {
            $v=array_change_key_case($v,CASE_LOWER );//键名统一转小写
            $fields[$v['field']] = $v['type'];
        }
        return $fields;
    }      
    public function addFieldSql($field_type, $field) {
        //表名
        $tablename = $field['tablename'];
        //字段名
        $fieldname = $field['fieldname'];
        //长度
        $fieldlen = $field['fieldlen'];
        switch ($field_type) {            
            case "varchar":
                if (!$fieldlen) {
                    $fieldlen = 255;
                }
                $fieldlen = min($fieldlen, 255);
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` VARCHAR( {$fieldlen} ) DEFAULT ''";
                Db::execute($sql);
                break;
            case "tinyint":
                if (!$fieldlen) {
                    $fieldlen = 3;
                }
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` TINYINT( {$fieldlen} ) UNSIGNED NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "smallint":
                $minnumber = intval($minnumber);
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` SMALLINT( {$fieldlen} ) UNSIGNED NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "mediumint":
                $minnumber = intval($minnumber);
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` INT ( {$fieldlen} ) UNSIGNED NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "int":
                $minnumber = intval($minnumber);
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` INT ( {$fieldlen} ) UNSIGNED NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "mediumtext":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` MEDIUMTEXT";
                Db::execute($sql);
                break;
            case "text":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` TEXT";
                Db::execute($sql);
                break;
            case "date":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` DATE DEFAULT ''";
                Db::execute($sql);
                break;
            case "datetime":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP";
                Db::execute($sql);
                break;
            case "timestamp":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP";
                Db::execute($sql);
                break;
            case "double":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` DOUBLE NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "float":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` FLOAT( {$fieldlen} ) NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "bigint":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}` BIGINT( {$fieldlen} ) NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "longtext":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}`  LONGTEXT";
                Db::execute($sql);
                break;
            case "char":
                $sql = "ALTER TABLE `{$tablename}` ADD `{$fieldname}`  CHAR( {$fieldlen} ) DEFAULT ''";
                Db::execute($sql);
                break;
            default:
                return false;
                break;
        }
        return true;
    } 
    /**
     * 执行数据库表结构更改
     * @param type $field_type 字段类型
     * @param type $field 相关配置
     * $field = array(
     *      'tablename' 表名(完整表名)
     *      'newfilename' 新字段名
     *      'oldfilename' 原字段名
     *      'maxlength' 最大长度
     *      'minlength' 最小值
     *      'defaultvalue' 默认值
     *      'minnumber' 是否正整数 和整数 1为正整数，-1是为整数
     *      'decimaldigits' 小数位数
     * )
     */
    public function editFieldSql($field_type, $field) {      
        //表名
        $tablename = $field['tablename'];
        //原字段名
        $oldfilename = $field['oldfieldname'];
        //新字段名
        $newfilename = $field['newfieldname'] ? $field['newfieldname'] : $oldfilename;
        //长度
        $fieldlen = $field['fieldlen'];
        if (empty($tablename) || empty($newfilename)) {
            $this->error("表名或者字段名不能为空！");
            return false;
        }

        switch ($field_type) {
            case 'varchar':
                //最大值
                if (!$fieldlen) {
                    $fieldlen = 255;
                }
                $fieldlen = min($fieldlen, 255);
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` VARCHAR( {$fieldlen} ) DEFAULT ''";
                Db::execute($sql);
                break;
            case 'tinyint':
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` TINYINT( {$fieldlen} ) UNSIGNED NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case 'smallint':
                $minnumber = intval($minnumber);
                $defaultvalue = intval($defaultvalue);
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` SMALLINT ( {$fieldlen} ) UNSIGNED  NOT NULL DEFAULT '{$defaultvalue}' DEFAULT 0";
                Db::execute($sql);
                break;
            case 'mediumint':
                $minnumber = intval($minnumber);
                $defaultvalue = intval($defaultvalue);
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` MEDIUMINT ( {$fieldlen} ) UNSIGNED  NOT NULL DEFAULT '{$defaultvalue}' DEFAULT 0";
                Db::execute($sql);
                break;
            case 'int':
                $minnumber = intval($minnumber);
                $defaultvalue = intval($defaultvalue);
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` INT ( {$fieldlen} ) NOT NULL DEFAULT '{$defaultvalue}' DEFAULT 0";
                Db::execute($sql);
                break;
            case 'mediumtext':
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` MEDIUMTEXT";
                Db::execute($sql);
                break;
            case 'text':
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` TEXT";
                Db::execute($sql);
                break;
            case 'date':
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` DATE DEFAULT ''";
                Db::execute($sql);
                break;
            case 'datetime':
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP";
                Db::execute($sql);
                break;
            case 'timestamp':
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP";
                Db::execute($sql);
                break;
            case "double":
                $defaultvalue = intval($defaultvalue);
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` DOUBLE NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "float":
                $defaultvalue = intval($defaultvalue);
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}` FLOAT(" . $minnumber . ") NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "bigint":
                $defaultvalue = intval($defaultvalue);
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}`  BIGINT NOT NULL DEFAULT 0";
                Db::execute($sql);
                break;
            case "longtext":
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}`  LONGTEXT";
                Db::execute($sql);
                break;
            case "char":
                $sql = "ALTER TABLE `{$tablename}` CHANGE `{$oldfilename}` `{$newfilename}`  CHAR(" . $fieldlen . ") DEFAULT ''";
                Db::execute($sql);
                break;
            default:
                $this->error("不存在相关字段信息");
                return false;
                break;
        }
        return true;
    }   
        /**
     * 根据字段类型，删除对应的字段到相应表里面
     * @param type $filename 字段名称
     * @param type $tablename 完整表名
     */
    public function deleteFieldSql($field, $table_name) {
        if (!table_exists($table_name)) {
            $this->error("该表表不存在!");
        }
        $all_table_name=config('database.connections.mysql.prefix').$table_name;
        $sql = "ALTER TABLE `{$all_table_name}` DROP `{$field}`;";
        Db::execute($sql);
    }      
    /*
     * 创建字段html代码
     */
    public function createFieldHtmlCode($data){ 
        if(isset($data['field_id'])){
            $info=Db::name("feedback_field")->find($data['field_id']);
            //当字段类型 and 宽度 and 高度 and 默认值 未改变的时候htmlcode等于提交过来的，否则执行重新生成动作
            if(
                $data['htmlcode']
                &&$info['field']==$data['field']
                &&$info['name']==$data['name']
                &&$info['formtype']==$data['formtype']
                &&$data['formtype']!="morevalue"
                &&$info['formwidth']==$data['formwidth']
                &&$info['formheight']==$data['formheight']
                &&$info['defaultval']==$data['defaultval']
                &&$info['tips']==$data['tips']
                &&$info['imgwidth']==$data['imgwidth']
            ){
                $htmlcode=$data['htmlcode'];
            }else{
                $htmlcode=$this->FieldHtmlCodeReplace($data);
            }
        }else{
             $htmlcode=$this->FieldHtmlCodeReplace($data);
        }
        return $htmlcode;
    }
        /*
     * 替换字段类型的代码
     * 
     */
    public function FieldHtmlCodeReplace($rs){
        $field_temp= file_get_contents(base_path().self::modelFieldPath.$rs['formtype'].".php");
        //内容替换
        $field_temp=  str_replace("{modelFieldTemp_field}",$rs['field'],$field_temp);
        $field_temp=  str_replace("{tips}",$rs['tips'],$field_temp);
        $field_temp=  str_replace("{defaultval}",$rs['defaultval'],$field_temp);
        //宽度
        if($rs['formwidth']){
            $style_formwidth="width:".$rs['formwidth']."%;";
        }else{
            $style_formwidth="";
        }
        $field_temp=  str_replace("{style_formwidth}",$style_formwidth,$field_temp);
        //高度
        if($rs['formheight']){
            $style_formheight="height:".$rs['formheight']."px;";
        }else{
            $style_formheight="";
        }
        $field_temp=  str_replace("{style_formheight}",$style_formheight,$field_temp);
        //编辑器高度 宽度替换（因为编辑器只调用数值，不需要css样式）
        $field_temp=  str_replace("{imgwidth}",$rs['imgwidth'],$field_temp);
        $field_temp=  str_replace("{imgheight}",$rs['imgheight'],$field_temp);
        $field_temp=  str_replace("{formwidth}",$rs['formwidth']."%",$field_temp);
        $field_temp=  str_replace("{formheight}",$rs['formheight']?$rs['formheight']:500,$field_temp);
        //图片上传高度宽度替换
        
        //checkbox radio select选项替换
        $checkbox_option="";
        if($rs['formtype']=="checkbox"||$rs['formtype']=="radio"||$rs['formtype']=="select"||$rs['formtype']=="selects"){
            if($rs['defaultval']){
                $defaultval=explode("\r\n",$rs['defaultval']);                
                foreach($defaultval as $v){                    
                    $dufault_arr=explode(":",$v);
                    $option_arr=explode("==",$dufault_arr[0]);                    
                    $select_checked=$dufault_arr[1]=="default"?'{$r?"":"selected"}':"";//select 默认选择中的
                    $checked_default=$dufault_arr[1]=="default"?'{$r?"":"checked"}':"";//checked radio 默认选择中的
                    $option_name=trim($option_arr[0]);//字段名称
                    $option_value=trim($option_arr[1]==""?$option_arr[0]:$option_arr[1]);//字段值 为空时=名称
                    if($rs['formtype']=="checkbox"){
                        $checkbox_option.='<label><input type="checkbox"  name="'.$rs['field'].'[]" value="'.$option_value.'" title="'.$option_name.'" {:strstr($r[\''.$rs['field'].'\'],\'|'.$option_value.'|\')?"checked":""} '.$checked_default.'/>'.$option_name.'</label>';
                    }
                    if($rs['formtype']=="radio"){
                        $checkbox_option.='<label><input type="radio"  name="'.$rs['field'].'" value="'.$option_value.'" title="'.$option_name.'" {:$r[\''.$rs['field'].'\']==\''.$option_value.'\'?"checked":""} '.$checked_default.'/>'.$option_name.'</label>';                        
                    }  
                    if($rs['formtype']=="select"){
                        $checkbox_option.='<option value="'.$option_value.'" {$r[\''.$rs['field'].'\']==\''.$option_value.'\'?"selected":""} '.$select_checked.'>'.$option_name.'</option>';
                    }
                    if($rs['formtype']=="selects"){
                        $checkbox_option.='<option value="'.$option_value.'" {:strstr($r[\''.$rs['field'].'\'],\'|'.$option_value.'|\')?"selected":""} '.$select_checked.'>'.$option_name.'</option>';                        
                    }                      
                    
                }                
            }
            $field_temp=  str_replace("{select_option}",$checkbox_option,$field_temp);
        }
        //多值字段替换
        if($rs['formtype']=="morevalue"){
            $morevalue_name=$rs["morevalue_name"];//字段名
            $morevalue_type=$rs["morevalue_type"];//字段类型
            $morevalue_defaultvalue=$rs["morevalue_defaultvalue"];//默认值
            $morevalue_width=$rs["morevalue_width"];//宽度
            $name_str="";$form_str="";$form_str_js="";
            foreach($morevalue_name as $k=>$v){
                //标题
                $morevalue_width[$k]=intval($morevalue_width[$k]);
                $name_str.='<th style="width:'.($morevalue_width[$k]?$morevalue_width[$k]:10).'%">'.$morevalue_name[$k].'<input type="hidden" name="'.$rs['field'].'_morevalue_len[]" placeholder="我只是用于在保存信息的时候用来判断一共有几个morevalue字段的"></th>';
                //字段表单--------------
                //下拉菜单
                if($morevalue_type[$k]=="select"){
                    $form_str.='<td class="morevalue_select"><select class="layui-input" lay-ignore name="'.$rs['field'].'_'.$k.'[]">';
                    $form_str_js.='<td class="morevalue_select"><select class="layui-input" lay-ignore name="'.$rs['field'].'_'.$k.'[]">';
                    $defaultval=explode("\r\n",$morevalue_defaultvalue[$k]);
                    foreach($defaultval as $v2){
                        $dufault_arr=explode(":",$v2);
                        $option_arr=explode("==",$dufault_arr[0]);                    
                        $select_checked=$dufault_arr[1]=="default"?'<?=$r?"":"selected"?>':"";//select 默认选择中的
                        $checked_default=$dufault_arr[1]=="default"?'<?=$r?"":"checked"?>':"";//checked radio 默认选择中的
                        $option_name=trim($option_arr[0]);//字段名称
                        $option_value=trim($option_arr[1]==""?$option_arr[0]:$option_arr[1]);//字段值 为空时=名称                        
                        $form_str.='<option value="'.$option_value.'" <?=$vs[\''.$k.'\']==\''.$option_value.'\'?"selected":""?> '.$select_checked.'>'.$option_name.'</option>';
                        $form_str_js.='<option value="'.$option_value.'" '.$select_checked.'>'.$option_name.'</option>';
                    }
                    $form_str.='</td>';
                    $form_str_js.='</td>';
                }
                //文本域
                else if($morevalue_type[$k]=="textarea"){
                    $form_str.='<td class="morevalue_textarea"><textarea class="layui-input" name="'.$rs['field'].'_'.$k.'[]"><?=$r?$vs[\''.$k.'\']:\''.$morevalue_defaultvalue[$k].'\'?></textarea></td>';
                    $form_str_js.='<td class="morevalue_textarea"><textarea class="layui-input" name="'.$rs['field'].'_'.$k.'[]">'.$morevalue_defaultvalue[$k].'</textarea></td>';
                //文本框                  
                }else {                
                    $form_str.='<td class="morevalue_input"><input class="layui-input" placeholder="" value="<?=$r?$vs[\''.$k.'\']:\''.$morevalue_defaultvalue[$k].'\'?>" name="'.$rs['field'].'_'.$k.'[]"></td>';
                    $form_str_js.='<td class="morevalue_input"><input class="layui-input" placeholder="" value="'.$morevalue_defaultvalue[$k].'" name="'.$rs['field'].'_'.$k.'[]"></td>';
                }
            }
            $name_str.='<th style="width:10%">操作</th>';
            $form_str.='<td class="morevalue_button"><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_add(this,'.$rs['field'].'_form_js)">+</a><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_del(this)">-</a></td>';
            $form_str_js.='<td class="morevalue_button"><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_add(this,'.$rs['field'].'_form_js)">+</a><a class="layui-btn layui-btn-primary layui-btn-sm" onclick="morevalue_del(this)">-</a></td>';        
            $field_temp=  str_replace("{morevalue_fieldName}",$name_str,$field_temp);
            $field_temp=  str_replace("{morevalue_fieldForm}",$form_str,$field_temp);
            $field_temp=  str_replace("{morevalue_fieldFormJs}",str_replace("'","\'",$form_str_js),$field_temp);//替换formjs，用于多值字段增加的js
        }        
        
        return $field_temp;
    } 
    //morevalue类型字段，将数据处理存入defaultvalue字段里
    public function detailMorevalueDefaultval($data){
        $defaultvalue="";
        $morevalue_name=$data["morevalue_name"];
        $morevalue_type=$data["morevalue_type"];
        $morevalue_defaultvalue=$data["morevalue_defaultvalue"];
        $morevalue_width=$data["morevalue_width"];
        foreach($morevalue_name as $key=>$val){
            if($defaultvalue){
                $defaultvalue.="{{RsSplit}}".$morevalue_name[$key]."{{FieldSplit}}".$morevalue_type[$key]."{{FieldSplit}}".$morevalue_defaultvalue[$key]."{{FieldSplit}}".$morevalue_width[$key];
            }else{
                $defaultvalue =$morevalue_name[$key]."{{FieldSplit}}".$morevalue_type[$key]."{{FieldSplit}}".$morevalue_defaultvalue[$key]."{{FieldSplit}}".$morevalue_width[$key];
            }
        }
        return $defaultvalue;
    }     
}
